import {
    getUserProfile,
    updateUserPhoto,
    updateUserProfile,
} from "@/store/actions/profile";
import { useInitialState } from "@/utils/use-initial-state";
import {
    Button,
    List,
    DatePicker,
    NavBar,
    Popup,
    Toast,
    Dialog,
} from "antd-mobile";
import classNames from "classnames";
import { useHistory } from "react-router-dom";
import EditInput from "./components/EditInput";
import { useRef, useState } from "react";
import styles from "./index.module.scss";
import { useDispatch } from "react-redux";
import EditList from "./components/EditList";
import dayjs from "dayjs";
import { logout } from "@/store/actions/login";
const Item = List.Item;
type InputPopup = {
    type: "" | "name" | "intro";
    value: string;
    visible: boolean;
};
type ListPopup = {
    type: "" | "gender" | "photo";
    visible: boolean;
};
const ProfileEdit = () => {
    const { userProfile } = useInitialState(getUserProfile, "profile");
    const { photo, name, intro, gender, birthday } = userProfile;
    const history = useHistory();
    const dispatch = useDispatch();
    // 储存name intro 内容
    const [inputPopup, setInputPopup] = useState<InputPopup>({
        type: "",
        value: "",
        visible: false,
    });
    // 昵称控件显示
    const onInputShow = () => {
        setInputPopup({
            type: "name",
            value: name,
            visible: true,
        });
    };
    // 控件隐藏
    const onInputHide = () => {
        setInputPopup({
            type: "",
            value: "",
            visible: false,
        });
    };
    // 显示简介
    const onIntroShow = () => {
        setInputPopup({
            type: "intro",
            value: intro,
            visible: true,
        });
    };
    // 显示上传头像
    const fileRef = useRef<HTMLInputElement>(null);
    // 修改头像
    const onChangePhoto = async (e: React.ChangeEvent<HTMLInputElement>) => {
        // console.log('选择的头像为：', e.target.files)
        if (!e.target.files) {
            return Toast.show({
                content: "请选择要上传的头像",
                duration: 1000,
            });
        }
        const formData = new FormData();
        formData.append("photo", e.target.files[0]);
        await dispatch(updateUserPhoto(formData));
        onGenderHide();
        Toast.show({
            content: "上传成功",
            duration: 600,
        });
    };
    // 更新个人资料
    const onUpdateProfile = async (
        type: "name" | "intro" | "gender" | "photo" | "birthday",
        value: string
    ) => {
        if (type === "photo") {
            fileRef.current?.click();
        } else {
            await dispatch(updateUserProfile({ [type]: value }));
            Toast.show({
                content: "更新成功",
                duration: 1000,
            });
            // 关闭弹出层
            onInputHide();
            onGenderHide();
        }
    };
    // 储存gender photo 内容
    const [listPopup, setListPopup] = useState<ListPopup>({
        type: "",
        visible: false,
    });
    //显示性别
    const onGenderShow = () => {
        setListPopup({
            type: "gender",
            visible: true,
        });
    };
    // 隐藏性别
    const onGenderHide = () => {
        setListPopup({
            type: "",
            visible: false,
        });
    };
    //显示头像
    const onPhotoShow = () => {
        setListPopup({
            type: "photo",
            visible: true,
        });
    };
    const [showBirthday, setShowBirthday] = useState(false);
    //显示生日
    const onBirthdayShow = () => {
        setShowBirthday(true);
    };
    //隐藏生日
    const onBirthdayHide = () => {
        setShowBirthday(false);
    };
    // 更换生日
    const onUpdateBirthday = (value: Date) => {
        const birthday = dayjs(value).format("YYYY-MM-DD");
        onUpdateProfile("birthday", birthday);
        onBirthdayHide();
    };
    // 退出登录
    const onLogout = () => {
        const handler = Dialog.show({
            title: "温馨提示",
            content: "亲，你确定退出吗？",
            actions: [
                [
                    {
                        key: "cancel",
                        text: "取消",
                        onClick: () => {
                            handler.close();
                        },
                    },
                    {
                        key: "confirm",
                        text: "退出",
                        onClick: () => {
                            dispatch(logout());
                            handler.close();
                            history.replace("/login");
                        },
                        style: {
                            color: "var(--adm-color-weak)",
                        },
                    },
                ],
            ],
        });
    };
    return (
        <div className={styles.root}>
            <div className="content">
                {/* 标题 */}
                <NavBar
                    style={{
                        "--border-bottom": "1px solid #F0F0F0",
                    }}
                    onBack={() => history.go(-1)}>
                    个人信息
                </NavBar>
                <div className="wrapper">
                    {/* 列表 */}
                    <List className="profile-list">
                        {/* 列表项 */}
                        <Item
                            onClick={onPhotoShow}
                            extra={
                                <span className="avatar-wrapper">
                                    <img
                                        width={24}
                                        height={24}
                                        src={photo}
                                        alt=""
                                    />
                                </span>
                            }
                            arrow>
                            头像
                        </Item>
                        <Item arrow extra={name} onClick={onInputShow}>
                            昵称
                        </Item>
                        <Item
                            arrow
                            onClick={onIntroShow}
                            extra={
                                <span
                                    className={classNames(
                                        "intro",
                                        intro && "normal"
                                    )}>
                                    {intro ? intro : "未填写"}
                                </span>
                            }>
                            简介
                        </Item>
                    </List>

                    <List className="profile-list">
                        <Item
                            onClick={onGenderShow}
                            arrow
                            extra={gender + "" === "0" ? "男" : "女"}>
                            性别
                        </Item>
                        <Item arrow extra={birthday} onClick={onBirthdayShow}>
                            生日
                        </Item>
                    </List>

                    <DatePicker
                        visible={showBirthday}
                        value={new Date(birthday)}
                        onCancel={onBirthdayHide}
                        title="选择年月日"
                        min={new Date(1900, 0, 1, 0, 0, 0)}
                        max={new Date()}
                        onConfirm={onUpdateBirthday}
                    />
                </div>

                <div className="logout">
                    <Button className="btn" onClick={onLogout}>
                        退出登录
                    </Button>
                </div>
            </div>
            {/* 修改昵称 简介弹层 */}
            <Popup visible={inputPopup.visible} destroyOnClose position="right">
                <EditInput
                    onClose={onInputHide}
                    value={inputPopup.value}
                    type={inputPopup.type}
                    key={inputPopup.type}
                    onUpdateProfile={onUpdateProfile}
                />
            </Popup>
            <Popup visible={listPopup.visible} onMaskClick={onGenderHide}>
                <EditList
                    type={listPopup.type}
                    onClose={onGenderHide}
                    onUpdateProfile={onUpdateProfile}
                />
            </Popup>
            <input type="file" onChange={onChangePhoto} hidden ref={fileRef} />
        </div>
    );
};

export default ProfileEdit;
